<script setup lang="ts">
import { ref, reactive, onMounted, triggerRef, computed, watch, toRaw } from 'vue';
import bus from '../tools/bus';
import type * as VideoType from '../type';
import * as VideoApi from "../http/videoLabel";
import { Message } from '@arco-design/web-vue';
import Dialog from "@/components/dialog/index.vue";
import {
  usePageType
} from '../tools/usePageType';
const { isView, isCreate, isEdit } = usePageType();

const props = defineProps({
  toolData: {
    type: Array<VideoType.ToolItem>,
    default: () => {
      return [];
    },
  },
  isDisabled: {
    type: Boolean,
    default: false
  },
  scrapList: {
    type: Array<{name: string; value: string}>
  },
  sarIdList: {
    type: Array<string>,
    default: []
  },
  taskInfo: {
    type: Object,
    default: {}
  },
  currnetSeriesResultInfo: {
    type: Object,
    default: {}
  },
  getData: {
    type: Function,
    default: () => {}
  },
  submitVisible: {
    type: Boolean,
    default: false
  },
  currentNidus:{
    type: Object,
    default: {}
  },
  currentVideoListIndex:{
    type: Number,
    default: 0
  }
});

const emits = defineEmits(['update:submitVisible', 'update:isReject'])
//自带的工具（非接口提供）
const baseTools: VideoType.ToolItem[] = [
  { name: '调窗', toolName: 'Wwwc', iconName: "tiaochuang1", disabled: false, isSeleted: false, active: false, value: "" },
  { name: "", toolName: "", iconName: "", disabled: false, active: false, value: "" },//窗宽窗位下拉框
]

const clickToolitem = (item:any, index:number,)=> {
  if(item.disabled) return
  if( item.toolName === 'needTrace' && !isView){
    handleTrace()
    return
  }
  if( item.toolName !== "Wwwc" ) return;
  const isSeleted = !item.isSeleted;
  props.toolData.forEach((item: VideoType.ToolItem) => {
    item.active = false;
    item.value = "";
  })

  item.isSeleted = isSeleted;
  currentTool.value = item.isSeleted ? item.toolName : "";
  const changeData = {
    color: "",
    toolName: isSeleted ? item.toolName : "",
    isSeleted: item.isSeleted,
  }
  
  bus.emit("Tools.change", changeData);
}

onMounted(()=>{
  bus.on("NidusList.clickNidus", (thirdItem: any)=> {
    clickNidus(thirdItem.toolName, thirdItem.nidusName);
  });
})

function clickNidus(toolName:string, nidusName:string){
  const item = props.toolData.find((item:VideoType.ToolItem) => item.toolName === toolName);
  if( item ){
    clickTool(item, nidusName);
  }
}

const currentTool = ref(null);
const clickTool = (item:any, value:any) => {
  if( !item.toolName || item.disabled || props.isDisabled ) return;
  currentTool.value = item.toolName;
  const isSeleted = !item.isSeleted;
  props.toolData.forEach((item: VideoType.ToolItem) => {
    item.isSeleted = false;
    item.active = false;
    item.value = "";
  })
  item.active = true;
  item.isSeleted = isSeleted;

  const subItem = item.labelList.find((subItem:any)=> subItem.name === value)
  const changeData = {
    imageAnnotationId: subItem.imageAnnotationId,
    imageAnnotationToolId: subItem.imageAnnotationToolId,
    color: subItem.color,
    toolName: item.toolName,
    nidusName: subItem.name,
  }
  
  bus.emit("Tools.change", changeData);
}

function getClassName(item:any){
  if( !item.toolName ) return'wl';
  if( item.disabled ) return 'item disabled';
  if( isView && item.toolName === "needTrace" ) return 'item disabled';
  if( item.toolName !== "Wwwc" && item.toolName !== "needTrace" && props.isDisabled ) return 'item disabled';
  return currentTool.value !== item.toolName ?  'item' : 'item active';
}

function submitscrap(){
  if( isView ) return;
  visible.value = true;
}

const visible = ref(false);

// 废片原因
const discardCode = ref('');
// 废片原因备注
const discardReason = ref('');
interface CallBackData {
    done(closed: boolean): void | boolean | Promise<void | boolean>;
    flag: boolean;
    status: string;
}
const errStauts = ref(false);
// 提交废片
const handleMarkScrapVisible = async (data: CallBackData) => {
  if (data.status === 'clear') {
    discardCode.value = '';
    discardReason.value = '';
    errStauts.value = false;
    visible.value = data.flag;
  } else {
    data.done(true);
    if (discardCode.value) {
      // 提交废片
      errStauts.value = false;
      if(discardCode.value === '99' && discardReason.value == ''){
        Message.error({
          content: '请输入其他废片原因',
          closable: true,
          duration: 3000,
        })
        return
      }
      const params = {
        sarIdList: props.sarIdList.join(','),
        discardCode: discardCode.value,
        discardReason: discardReason.value
      }
      const result = await VideoApi.saveDiscard(params);
      visible.value = data.flag;
      // 弹出提交窗
      emits('update:submitVisible', true);
      emits('update:isReject', true);
    } else {
      errStauts.value = true;
    }
  }
}

const handleYayClick = async (type: number) => {
  const params = {
    sarIdList: props.sarIdList.join(','),
    yayAttributes: type
  }
  const result = await VideoApi.updateYay(params);
  !result && props.getData && props.getData();
}

//loading弹出框
const loadVisible = ref(false)
const traceTipVisible = ref(false)
const tipContent = ref('')
const tip1 = '请确认是否有标注帧段'
const tip2 = '请确认起始、结束、关键帧是否有标注框'
const tip3 = '请确认起始、结束、关键帧是否存在多个标注框'
//追踪按钮
const handleTrace = () =>{
  //validate 判断逻辑
  // console.log("当前序列帧段", props.currentNidus)
  if(props.currentNidus.child.length === 0){
    tipContent.value = tip1
    traceTipVisible.value = true
    return
  }
  const { child } = props.currentNidus
  let validate = ''
  let invalidateItem = null
  let subIndex = -1
  for(let [index,item] of child.entries()){
    const {startIndex, endIndex, child} = item
    //有且仅有三个非算法框-toolname：RectangleRoi分布在不同index
    const rectArr = child.filter(({toolName,alg}:{toolName: string;alg:boolean})=> toolName === 'RectangleRoi' && !alg)
    rectArr.sort((a:any,b:any)=> a.labelIndex - b.labelIndex)
    //多了
    if(rectArr.length > 3){
      validate = 'tip3'
      invalidateItem = item
      subIndex = index
      break
    }
    //不在特定位置
    if(!rectArr[0] || !rectArr[1] || !rectArr[2]
        || (startIndex !==rectArr[0].labelIndex)
        || (endIndex !== rectArr[2].labelIndex)
        || (startIndex >= rectArr[1].labelIndex)
        || (endIndex <= rectArr[1].labelIndex)
    ){
      validate = 'tip2'
      invalidateItem = item
      subIndex = index
      break
    }
  }
  if(validate === 'tip2'){
    tipContent.value = tip2
    traceTipVisible.value = true
    //定位到对应帧段
    bus.emit("NidusList.changeSubItemActive", [props.currentVideoListIndex, subIndex, true]);
    return
  }
  if(validate === 'tip3'){
    tipContent.value = tip3
    traceTipVisible.value = true
    //定位到对应帧段
    bus.emit("NidusList.changeSubItemActive", [props.currentVideoListIndex, subIndex, true]);
    return
  }
  //如何判断是否修改过？后端判断，考虑刷新等情况
  //通过验证，开始追踪
  loadVisible.value = true
  VideoApi.algorithmTrace({sarId: props.currentNidus.sarId}).then((res)=>{
    if( res == undefined){
      //成功后刷新列表
      Message.success("追踪成功")
      // console.log("after api",cornerstoneTools.globalImageIdSpecificToolStateManager.toolState)
      bus.emit('NidusList.refresh')
    }
    loadVisible.value = false
  }).finally(() => {
    loadVisible.value = false
  })
}
</script>


<template>
  <div class="video-tool">
    <div class="left">
      <div 
        :class="getClassName(item)"
        v-for="(item, index) in baseTools.concat(props.toolData)"
        :key="item.toolName"
        :disabled="item.disabled"
        @click="clickToolitem(item,index)"
      >
        <div class="icon-container" v-if="item.toolName" >
          <i :class="`iconfont icon-${item.iconName}`"></i>
        </div>
        <span class="icon-text" v-if="item.toolName" >{{ item.name }}</span>
        <a-select v-model="item.value" :disabled="item.disabled || props.isDisabled" v-if="item.toolName && item.toolName !== 'Wwwc' && item.toolName !== 'needTrace'" @change="(value:any)=> clickTool(item, value)" >
          <a-tooltip v-for="(subItem, subIndex) in item.labelList || []" :key="subIndex" :content="subItem.name" position="right">
            <a-option
              :label="subItem.name" 
            />
          </a-tooltip>
        </a-select>
        <a-select v-if="!item.toolName" :style="{width:'73px', height: '22px'}" placeholder="选择窗位">
          <a-option>CT窗位</a-option>
          <a-option>CT肺窗</a-option>
        </a-select>
      </div>
    </div>
    <div class="right-box">
      <div class="yay-box" v-if="taskInfo.isYayAttributes">
        <span :class="currnetSeriesResultInfo.yayAttributes === 1 ? 'active' : ''" @click="() => { (isCreate || isEdit)  && handleYayClick(1)}">阴性</span>
        <span :class="currnetSeriesResultInfo.yayAttributes === 2 ? 'active' : ''" @click="() => { (isCreate || isEdit) && handleYayClick(2)}">阳性</span>
      </div>
      <div class="right" @click="submitscrap" v-if="scrapList?.length !== 0">
        <i class="iconfont icon-feipian"></i>
        <div :class=" isView ? 'text disabled' : 'text' " :disabled="isView" >标记废片</div>
        <!-- 标记废片弹窗 -->
        <Dialog
          :visible="visible"
          :title="'标记废片'"
          :width="502"
          :maskClosable="false"
          :isForm="true"
          :modalClass="'mark-scrap-dialog'"
          :okText="'提交'"
          @update:visible="handleMarkScrapVisible"
        >
          <template v-slot>
            <div class="radio-container">
              <div class="radio-title">请选择该切片标为废片的原因</div>
              <div class="radio-group">
                <a-radio-group v-model="discardCode">
                  <a-radio
                    class="radio-group-item"
                    v-for="item in scrapList"
                    :key="item.value"
                    :value="item.value"
                    >{{ item.name }}</a-radio
                  >
                </a-radio-group>
              </div>
              <div class="err-tips" v-if="errStauts">请选择原因！</div>
              <div class="other-container" v-if="discardCode === '99'">
                <a-textarea
                  v-model="discardReason"
                  :auto-size="{ minRows: 2, maxRows: 2 }"
                  :max-length="200"
                  placeholder="请输入其他废片原因（必填）"
                ></a-textarea>
              </div>
            </div>
          </template>
        </Dialog>
      </div>
    </div>
    <a-modal v-model:visible="loadVisible" :closable="false" :simple="true" :footer="false" :mask-closable="false" :modal-style="{backgroundColor:'#393A3C',fontSize:'16px',color:'#FFFFFF',width:'328px'}">
      <div>
        <a-spin>
          <template #icon>
            <i class="iconfont arco-icon-spin icon-loading" style="font-size: 45px;color:#ffffff;display: inline-block"></i>
          </template>
        </a-spin>
        <p style="color:#ffffff;font-size:16px;">算法追踪中，请稍后...</p>
      </div>
    </a-modal>
    <a-modal v-model:visible="traceTipVisible" modal-class="traceTip" :hideCancel="true" :closable="true" okText="确认" :mask-closable="false" :modal-style="{backgroundColor:'#272727',fontSize:'16px',color:'#FFFFFF',width:'400px'}">
      <template #title><span  style="background: #393A3C;font-weight:600;width:100%;color:#FFFFFF;text-align:center;">提示</span></template>
      <div>
        <a-spin>
          <template #icon>
            <i class="iconfont icon-bingzaotishi" style="font-size: 16px;color:#FF7D00;display: inline-block;"></i>
          </template>
        </a-spin>
        <span style="color:#ffffff;font-size:16px;margin-left:10px;">{{tipContent}}</span>
      </div>
    </a-modal>
  </div>
</template>

<style lang="less">
.feipian-from{
  .arco-form-item-label-col{
    display: none;
  }
}
.traceTip{
  .arco-modal-header{
    background-color: #393A3C !important;
  }
}

.video-tool {
  width: 100%;
  height: 54px;
  background: #04101d;
  display: flex;
  // align-content: center;
  align-items: center;
  justify-content: space-between;
  padding: 0 20px;
  .right-box{
    display: flex;
    color: #ccc;
    align-items: center;
    .yay-box{
      margin-right: 8px;
      width: 80px;
      border: 1px solid #8ea7b2;
      border-radius: 2px;
      color: #cedee0;
      display: flex;
      align-items: center;
      justify-content: center;
      user-select: none;
      cursor: pointer;
      span{
        display: inline-block;
        width: 40px;
        height: 27px;
        margin: 0 auto;
        line-height: 27px;
        text-align: center;
        font-weight: 400;
        font-size: 12px;
      }
      span.active{
        color: #13fffb;
        background: #074452;
        box-shadow: inset 0px 0px 4px rgba(19, 255, 251, 0.15);
      }
    }
  }
  .right{
    text-align: center;
    cursor: pointer;
    padding-left: 20px;
    border-left: 1px solid rgba(255, 255, 255, 0.16);
    .text{
      color: #fff;
      //margin-top: -12px;
      &.disabled{
        cursor: not-allowed;
      }
    }
    .icon-feipian{
      color: #FAAD14;
      font-size: 26px;
    }
  }
  .left{
    display: flex;
  }
  .item{
    width: 60px;
    text-align: center;
    padding-top: 5px;
    cursor: pointer;
    position: relative;
    .iconfont{
      color: #fff;
      font-size: 30px;
    }
    .arco-select-view-single{
      position: absolute;
      top: 5px;
      left: 0;
      background: transparent !important;
      box-shadow: none;
      border: none !important;
      width: 50px;
      height: 100%;
      .arco-select-view-value{
        color: transparent;
      }
      .arco-select-view-suffix{
        color: transparent !important;
        display: none !important;
      }
    }
    &.active,
    &:hover{
      .icon-container{
        background: #074452;
      }
      .icon-text{
        color: #70E2F0;
      }
    }
    .arco-select-view-disabled{
      background-color: transparent !important;
    }
    &.disabled{
      .iconfont{
        color: #999;
      }
    }
    &.disabled:hover{
      cursor: not-allowed;
      .icon-container{
        background: transparent;
      }
      .icon-text{
        color: #9BB2BC;
      }
    }

    .icon-container{
      width: 30px;
      height: 30px;
      margin: 0 auto;
      display: flex;
      justify-content: center;
      align-items: center;
      border-radius: 4px;
    }
    .icon-text{
      display: block;
      color: #9BB2BC;
      font-size: 12px;
      line-height: 14px;
    }
  }
  .wl{
    display: flex;
    justify-content: center;
    align-items: center;
    padding-right: 12px;
    position: relative;
    &::after{
      content: "";
      display: block;
      width: 1px;
      height: 32px;
      background-color: rgba(255, 255, 255, 0.16);
      position: absolute;
      right: 0;
      top: 10px;
    }
    span.arco-select-view-single{
      background: transparent;
      border: 1px solid #D2EFFC;
      padding-left: 6px;
      padding-right: 3px;
      .arco-select-view-suffix{
        padding: 0;
      }
      .arco-select-view-input{
        font-size: 12px;
      }
      .arco-select-view-value{
        color: #fff;
        padding: 0;
        min-height: auto;
        font-size: 12px;
      }
    }
  }
}

.arco-trigger-popup.arco-trigger-position-bl{
  min-width: 150px;
  max-width: 150px;
  .arco-select-dropdown{
    padding: 0;
  }
  .arco-select-dropdown .arco-select-option{
    padding: 0 5px;
    background-color: transparent !important;
    &:hover{
      background-color: transparent !important;
    }
  }
  .arco-select-option-content{
    font-size: 12px;
  }
}
.mark-scrap-dialog.arco-modal{
  background-color: #272727;
  .arco-modal-header {
    height: 64px;
    background-color: #393a3c;
    font-weight: 700;
    font-size: 18px;
    color: #fff;
    border: 0;
    .arco-modal-title,
    .arco-modal-close-btn {
      font-weight: 700;
      font-size: 18px;
      color: #fff;
    }
    .arco-icon-hover:hover::before {
      background-color: #616367;
    }
  }
  .arco-modal-body {
    .radio-title {
      font-weight: 400;
      font-size: 16px;
      color: #fff;
      margin-bottom: 18px;
      text-align: left;
    }
    .radio-group {
      display: flex;
      align-items: center;
      justify-content: flex-start;
      .arco-radio-group {
        display: flex;
        align-items: center;
        justify-content: flex-start;
        flex-wrap: wrap;
        .radio-group-item {
          margin-bottom: 12px;
          .arco-radio-label {
            white-space: nowrap;
          }
        }
      }
      .arco-radio-icon {
        width: 12px;
        height: 12px;
        line-height: 12px;
        border: 1px solid rgba(255, 255, 255, 0.7);
      }
      .arco-radio-icon::after {
        background-color: transparent;
      }
      .arco-radio:hover .arco-radio-icon {
        border-color: #67c9d5;
      }
      .arco-radio:hover .arco-radio-icon-hover::before {
        background-color: transparent;
      }
      .arco-radio-checked .arco-radio-icon {
        border: 1px solid #67c9d5;
        background-color: transparent;
      }
      .arco-radio-checked .arco-radio-icon::after {
        background-color: #67c9d5;
      }
      &-item {
        font-weight: 400;
        font-size: 14px;
        color: #ccc;
        .arco-radio-label {
          color: #ccc;
        }
      }
    }
    .err-tips{
      font-size: 12px;
      color: #F40;
      text-align: left;
      margin-bottom: 8px;
    }
    .other-container {
      margin: 4px 0 20px;
      width: 100%;
      height: 32px;
      .arco-textarea-wrapper {
        background-color: transparent;
        border: 1px solid rgba(255, 255, 255, 0.7);
        color: #fff;
      }
    }
  }
  .arco-modal-footer {
    text-align: center;
    border: 0;
    .arco-btn {
      width: 96px;
      height: 40px;
      font-weight: 400;
      font-size: 16px;
      border-radius: 4px;
    }
    .arco-btn-secondary {
      background-color: transparent;
      border: 1px solid #d9d9d9;
      color: #FFF;
    }
    .arco-btn-secondary:hover,
    .arco-btn-secondary[type="button"]:hover{
      color: #448e97;
      background-color: #f0f9fa;
      border: 1px solid #f0f9fa;
    }
    .arco-btn-primary {
      background-color: #448e97;
      border-color: #448e97;
    }
    .arco-btn-primary:hover,
    .arco-btn-primary[type="button"]:hover {
      background-color: #67c9d5;
      border-color: #67c9d5;
    }
  }
}
.mark-scrap-dialog {
  .arco-modal-body {
    padding: 20px 32px;
  }
  .arco-modal-footer {
    padding: 0 20px 32px;
  }
}
</style>
